<template>
  <div id="root">
    <todo-header></todo-header>
    <todo-input
      @savetodo="handleSaveTodo"
      @allselect="handleAllSelect"
    ></todo-input>
    <div v-for="(item, index) in filterTodos" :key="item.id">
      <!-- index可以在删除需求的时候回传 -->
      <todo-item
        :item="item"
        :index="index"
        @deltodo="handleDeteTodo"
      ></todo-item>
    </div>
    <todo-tool
      @delcomplete="handleDelComplete"
      @changeTab="handleChangeTab"
      :remaining="remaining"
      :active-tab="activeTab"
    ></todo-tool>
  </div>
</template>

<script>
import Header from "./components/Header.vue";
import TodoInput from "@/components/TodoInput";
import TodoItem from "@/components/TodoItem";
import TodoTool from "@/components/TodoTool";
export default {
  computed: {
    filterTodos: function () {
      if (this.activeTab === "all") {
        return this.todos;
      } else if (this.activeTab == "active") {
        return this.todos.filter((v) => {
          return !v.complete;
        });
      } else if (this.activeTab == "complete") {
        return this.todos.filter((v) => {
          return v.complete;
        });
      }
    },
    remaining: function () {
      // 剩下多少项目 complete的false项
      /* let filterTodos= this.todos.filter(function(v){
        return !v.complete;   // complete false 就返回
      })
      return filterTodos.length; */
      return this.todos.filter(function (v) {
        return !v.complete; // complete false 就返回
      }).length;
    },
  },
  data: function () {
    return {
      activeTab: "all", // all全部  active激活 complete已完成
      todos: [
        {
          id: 1,
          text: "工藤新一",
          complete: true, // true表示todo已经完成 false表示没有完成
        },
        {
          id: 2,
          text: "毛利小五郎",
          complete: false, // true表示todo已经完成 false表示没有完成
        },
        {
          id: 3,
          text: "服部平次",
          complete: true, // true表示todo已经完成 false表示没有完成
        },
      ],
    };
  },
  methods: {
    // 删除已完成
    handleDelComplete: function () {
      // 删除已完成，过滤未完成的，再赋值给土豆丝
      let unCompleteTodos = this.todos.filter((v) => {
        return !v.complete;
      });
      this.todos = unCompleteTodos;
    },
    // 全选
    handleAllSelect: function () {
      this.todos.filter((v) => {
        v.complete = true;
      });
    },
    // 改变activeTab
    handleChangeTab: function (activeTab) {
      this.activeTab = activeTab;
    },
    // 父组件保存todo
    handleSaveTodo: function (item) {
      this.todos.push(item);
    },
    // 父组件删除todo
    handleDeteTodo: function (index) {
      this.todos.splice(index, 1);
    },
  },
  name: "App",
  components: {
    "todo-header": Header,
    "todo-input": TodoInput,
    "todo-item": TodoItem,
    "todo-tool": TodoTool,
  },
};
</script>

<style>
* {
  padding: 0;
  margin: 0;
}
#root {
  width: 800px;
  height: 600px;
  margin: 0 auto;
  background: #f5f5f5;
}
</style>
